//
//  ExaminationTool.m
//  VideoExam
//
//  Created by apple on 2020/4/13.
//

#import "TestManageTool.h"
#import "ParsingModel.h"
#import "PayModel.h"

@implementation TestManageTool
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static TestManageTool *instance = nil;
    dispatch_once(&onceToken,^{
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}
- (instancetype)init {
    self = [super init];
    if (self) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return self;
}

- (OrderModel *)orderModel {
    if (_orderModel == nil) {
        _orderModel=[[OrderModel alloc] init];
    }
    return _orderModel;
}

#pragma mark 创建订单
- (void)create_order_success:(ObjSuccess)successBlock error:(void(^)(NSString * info))errorBlock {
    //创建串行队列
       dispatch_queue_t seial_queue = dispatch_queue_create("my_queue", DISPATCH_QUEUE_SERIAL);
       //创建信号量
       dispatch_semaphore_t semaphore_t  = dispatch_semaphore_create(0);
       
      __block BOOL success = YES;
    __block NSString * error_info = @"";
       //上传学生二寸照片
       dispatch_async(seial_queue, ^{
           [self.student_model pictureImageSuccess:^(id obj) {
                dispatch_semaphore_signal(semaphore_t);
           } error:^{
                success =NO;
                error_info = @"2寸照片上传失败";
                dispatch_semaphore_signal(semaphore_t);
           }];
           dispatch_semaphore_wait(semaphore_t, DISPATCH_TIME_FOREVER);//不能再主线程中使用
       });
    
      if ([self.testModel.currentLevelModel need_certificate_image]) {//判断是否需要上传证书
        dispatch_async(seial_queue, ^{//上传证书图片
            if (success==NO) {
                  dispatch_semaphore_signal(semaphore_t);
                  return;
              }
            [self.testModel upload_certificate_image_Success:^(id obj) {
                dispatch_semaphore_signal(semaphore_t);
            } error:^{
                success =NO;
                error_info = @"证书上传失败";
                dispatch_semaphore_signal(semaphore_t);
            }];
            dispatch_semaphore_wait(semaphore_t, DISPATCH_TIME_FOREVER);//不能再主线程中使用
        });
    }
       
       //创建订单
       dispatch_async(seial_queue, ^{
           if (success==NO) {
               dispatch_semaphore_signal(semaphore_t);
               return;
           }
           NSMutableDictionary * submit_dic = [self get_submit_dic];
           [NetWorkTools jsonFormat_requestURLStr:Create_order_url params:submit_dic success:^(id responseObject) {//创建订单接口
               NSLog(@"创建订单 - %@",responseObject);
               if ([AppTools isStateSuccess:responseObject]) {
                   self.orderModel = [OrderModel yy_modelWithJSON:responseObject[@"data"]];//订单信息
               } else {
                   success =NO;
                    ParsingModel *model = [ParsingModel yy_modelWithJSON:responseObject];
                    error_info= model.msg;
               }
               dispatch_semaphore_signal(semaphore_t);
           } failure:^(NSError *error) {
               success =NO;
               dispatch_semaphore_signal(semaphore_t);
           }];
           dispatch_semaphore_wait(semaphore_t, DISPATCH_TIME_FOREVER);//不能再主线程中使用
       });
    
    
        dispatch_async(seial_queue, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    if (successBlock) {
                        successBlock(nil);
                    }
                } else {
                    if (errorBlock) {
                        errorBlock(error_info);
                    }
                }
            });
        });
}
//创建订单数据
- (NSMutableDictionary *)get_submit_dic {
    NSMutableDictionary *submit_dic = [[NSMutableDictionary alloc] init];
    self.student_model.gender =[self.student_model get_gender_number];
    NSDictionary * student_dic = [self.student_model yy_modelToJSONObject];
    NSMutableDictionary *mDic = [[NSMutableDictionary alloc] initWithDictionary:student_dic];
    [mDic removeObjectForKey:@"pictureImage"];
    [submit_dic setObject:mDic forKey:@"createUserDto"];
    
    //考试信息
    NSMutableDictionary * test_dic = [[NSMutableDictionary alloc] init];
    if ([self.testModel.currentLevelModel need_certificate_image] && [self.testModel.currentLevelModel.certificate_image_url isHelpful]) {
        [test_dic setObject:self.testModel.currentLevelModel.certificate_image_url forKey:@"certificatePicUrl"];
    }
    [test_dic setObject:self.testModel.currentLevelModel.Id forKey:@"levelId"];
    [test_dic setObject:self.testModel.currentLevelModel.price forKey:@"money"];
    [test_dic setObject:self.testModel.code forKey:@"referralCode"]; //考级码
    [test_dic setObject:self.testModel.currentProject.Id forKey:@"subjectId"];
    NSMutableArray * tuneIds = [NSMutableArray new];
    for (SongModel *model in self.testModel.selected_song_list) {
        [tuneIds addObject:model.Id];
    }
    [test_dic setObject:tuneIds forKey:@"tuneIds"];//曲目id数组
    [submit_dic setObject:test_dic forKey:@"createGradeDto"];

    NSLog(@"提交的字典 submit_dic - %@",submit_dic);
    return submit_dic;
}

//详情界面进入视频录制获取 视频组合路径
+ (void)details_vc_get_path_detailsModel:(OrderDetailsModel*)model {
    NSMutableString * url = [[NSMutableString alloc] init];
    //学尔空间
       NSString * company_name = @"云考级/";
      if (IS_DEBUG) {
          company_name = @"云考级_测试/";
      }
    //考级委员会
    NSString * committee_name = [NSString stringWithFormat:@"%@/",model.committeeName];
   //日期
    NSString *date_str = [NSString stringWithFormat:@"%@/",[AppTools getDateStrDate:[NSDate date] dateFormat:@"yyyy-MM-dd"]];
    //考生名字
    NSString *user_name =[NSString stringWithFormat:@"%@+",model.name];
    //手机号
    NSString *phone =[NSString stringWithFormat:@"%@+",model.phone];
    [url appendString:company_name];
    [url appendString:committee_name];
    [url appendString:date_str];
    [url appendString:user_name];
    [url appendString:phone];
    [TestManageTool sharedInstance].details_oss_path = url;
}


/// 设置 oss 服务器里的路径url 路径 上传的时候在拼接 视频名
/// @param details_push 是否是详情界面进入
+ (NSString *)Set_OSS_url_path_details_push:(BOOL)details_push {
//    学尔空间_测试/考级委员会/日期/考生名字+手机号+时间戳.mp4
    NSMutableString * url = [[NSMutableString alloc] init];
    //学尔空间
     NSString * company_name = @"云考级/";
    if (IS_DEBUG) {
        company_name = @"云考级_测试/";
    }
    
    if (details_push) {//详情进入
        NSString * oss_path = [TestManageTool sharedInstance].details_oss_path;
        GDLog(@"OSS_url_name %@",oss_path);
        return oss_path;

    }
        //考级委员会
        NSString * committee_name = [NSString stringWithFormat:@"%@/",[TestManageTool sharedInstance].testModel.project_info_model.committeeName];
        //日期
        NSString *date_str = [NSString stringWithFormat:@"%@/",[AppTools getDateStrDate:[NSDate date] dateFormat:@"yyyy-MM-dd"]];
        //考生名字
        NSString *user_name =[NSString stringWithFormat:@"%@+",[TestManageTool sharedInstance].student_model.name];
        //手机号
        NSString *phone =[NSString stringWithFormat:@"%@+",[TestManageTool sharedInstance].student_model.phone];
        //yyyyMMddHHss 时间戳 yyyy-MM-dd hh:mm:ss.SSS 到毫秒
        //         NSString *yyyyMMddHHss = [NSString stringWithFormat:@"%@.mp4",[AppTools getDateStrDate:[NSDate date] dateFormat:@"yyyyMMddHHss.SSS"]];

        [url appendString:company_name];
        [url appendString:committee_name];
        [url appendString:date_str];
        [url appendString:user_name];
        [url appendString:phone];
    
    
    
    NSString *url_name =url;
    GDLog(@"OSS_url_name %@",url_name);
    return url_name;
}

/// 创建微信
/// @param orderId  订单id
/// @param successBlock successBlock
/// @param errorBlock errorBlock
+ (void)weiXin_Create_Order_orderId:(NSString *)orderId success:(ObjSuccess)successBlock error:(ErrorBlock)errorBlock {

    NSString * url = [NSString stringWithFormat:@"%@%@",weiXin_Create_Order_url,orderId];
    [NetWorkTools requestWithURLStr:url method:GET params:nil success:^(id responseObject) {
          GDLog(@"微信创建订单 %@",responseObject);
              if ([AppTools isStateSuccess:responseObject]) {
                  PayModel *model = [PayModel yy_modelWithJSON:responseObject[@"data"]];
                  if (successBlock) {
                      successBlock(model);
                  }
              } else {
                  if (errorBlock) {
                      errorBlock();
                  }
              }
    } failure:^(NSError *error) {
        GDLog(@"微信创建订单error %@",error);
             if (errorBlock) {
                 errorBlock();
             }
    }];

}
/// 创建支付宝订单
/// @param orderId  订单id
/// @param successBlock successBlock
/// @param errorBlock errorBlock
+ (void)aliPay_Create_Order_orderId:(NSString *)orderId success:(ObjSuccess)successBlock error:(ErrorBlock)errorBlock{
    NSString *url = [NSString stringWithFormat:@"%@orderId=%@",aliPay_Create_Order_url,orderId];
    [NetWorkTools requestWithURLStr:url method:GET params:nil success:^(id responseObject) {
        if ([AppTools isStateSuccess:responseObject]) {
            PayModel *model = [PayModel yy_modelWithJSON:responseObject[@"data"]];
            if (successBlock) {
                successBlock(model);
            }
        } else {
            if (errorBlock) {
                errorBlock();
            }
        }
        GDLog(@"支付宝创建订单 %@",responseObject);
    } failure:^(NSError *error) {
         GDLog(@"支付宝创建订单error %@",error);
        if (errorBlock) {
            errorBlock();
        }
    }];
}


#pragma mark 修改订单状态 改为视频上传状态
/// 修改订单状态 改为视频上传状态
/// @param orderId 订单id
/// @param successBlock successBlock
/// @param errorBlock errorBlock
+ (void)change_order_state_orderId:(NSString *)orderId success:(ObjSuccess)successBlock error:(ErrorBlock)errorBlock {
    NSString *url = [NSString stringWithFormat:@"%@orderId=%@",change_order_state_url,orderId];
    [NetWorkTools requestWithURLStr:url method:GET params:nil success:^(id responseObject) {
        GDLog(@"修改订单状态 %@",responseObject);
        if ([AppTools isStateSuccess:responseObject]) {
               if (successBlock) {
                   successBlock(nil);
                }
           } else {
               if (errorBlock) {
                      errorBlock();
                  }
           }
    } failure:^(NSError *error) {
        if (errorBlock) {
            errorBlock();
        }
        NSString *errorStr = [self errorDescribe:error];
        [QMUITips showError:errorStr];
    }];
}

#pragma mark 完成考试
/// 完成考试
/// @param orderId 订单id
/// @param data 上传成功后的 视频model数组
/// @param successBlock successBlock
/// @param errorBlock errorBlock
+ (void)finish_test_orderId:(NSString *)orderId dataArray:(NSArray *)data success:(ObjSuccess)successBlock error:(ErrorBlock)errorBlock {
    NSMutableDictionary * parms =[NSMutableDictionary new];
    [parms setObject:orderId forKey:@"orderId"];
    NSMutableArray * array = [NSMutableArray new];
    for (VideoModel *model in data) {
        NSMutableDictionary * items =[NSMutableDictionary new];
        [items setObject:model.Id forKey:@"id"];
        [items setObject:model.coverImageUrl forKey:@"pic"];
        [items setObject:model.videoUrl forKey:@"url"];
        [array addObject:items];
    }
    [parms setObject:array forKey:@"videoDtoList"];
    [NetWorkTools jsonFormat_requestURLStr:finish_test_url params:parms success:^(id responseObject) {
        GDLog(@"完成考试%@",responseObject);
        if ([AppTools isStateSuccess:responseObject]) {
            if (successBlock) {
                successBlock(nil);
            }
        } else {
            if (errorBlock) {
                   errorBlock();
               }
        }
    } failure:^(NSError *error) {
        if (errorBlock) {
            errorBlock();
        }
        NSString *errorStr = [self errorDescribe:error];
        [QMUITips showError:errorStr];
    }];
}





@end

#pragma mark 订单model
@implementation OrderModel

@end



